<?php
	defined('RUN') or die('No access');
	
	class MemberModel
	{
		private $tables='member';
	    public function getMembers($fields='*')
		{
			return Model::getDataSql("SELECT ".$fields." FROM ".$this->tables." ORDER BY `updated` DESC, `id` DESC");
		}
		public function checkUser($username)
		{
			$sql = "SELECT COUNT(`id`) as `total` FROM ".$this->tables." WHERE `username`='".$username."'";
			$query = Db::query($sql);
			$result = Query::fetch($query);
			$total = $result['total'];
			if($total != 0)
				return TRUE;
			else
				return FALSE;
		}
		public function checkEmail($email)
		{
			$sql = "SELECT COUNT(`id`) as `total` FROM ".$this->tables." WHERE `email`='".$email."'";
			$query = Db::query($sql);
			$result = Query::fetch($query);
			$total = $result['total'];
			if($total != 0)
				return TRUE;
			else
				return FALSE;
		}
        public function countRows()
		{
			$sql = "SELECT COUNT(`id`) as `total` FROM ".$this->tables;
			$query = Db::query($sql);
			$result = Query::fetch($query);
			$total = $result['total'];
			
			return $total;
		}
		public function getByPage($fields='*', $page, $per_page = 20)
		{
			$order = '`updated` DESC, `id` DESC';
			$conditions='';
			$offset = ($page - 1) * $per_page;
			$data = Model::getData($this->tables, $fields, $conditions, $per_page, $offset, $order);
			return $data;
		}
		public function getById($id,$fields='*')
		{
			$condition = array(
					'field' => 'id',
					'value' => $id
				);

			$cat = Model::getData($this->tables, $fields, $condition);
			if ($cat)
				return $cat[0];

			return FALSE;
		}
		public function add($data)
		{
			return Model::insertData($this->tables, $data);
		}

		public function update($data, $id)
		{
			$condition = array(
					'field' => 'id',
					'value' => $id
				);
			
			return Model::updateData($this->tables, $data, $condition);
		}
		public function updateUser($data, $user)
		{
			$condition = array(
					'field' => 'username',
					'value' => $user
				);
			
			return Model::updateData($this->tables, $data, $condition);
		}
		public function delete($id)
		{
			$condition = array(
					'field' => 'id',
					'value' => $id
				);

			return Model::deleteData($this->tables, $condition);
		}
        
        
        public function getByUsername($username, $fields='*')
		{
			$condition = array(
					'field' => 'username',
					'value' => strtolower($username)
				);

			$users = Model::getData($this->tables, $fields, $condition);

			if (count($users) > 0)
				return $users[0];

			return FALSE;
		}
        
        public function checkAuth($username, $password)
		{
			$user = $this->getByUsername($username,'`password`');

			if ($user)
			{
				if ($user['password'] == Security::hash($password))
				{
                    return 	$user = $this->getByUsername($username,'`id`');
				}
			}

			return FALSE;
		}
	}
